package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01用户模块")
@Slf4j
@RestController
@RequestMapping(value = "/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("注册功能")
    @PostMapping(value = "reg")
    public JsonResult usersReg(@RequestBody @Validated UserRegDTO userRegDTO) {
        log.debug("userRegDTO");
        UserVO uservo = userMapper.selectByUsername(userRegDTO.getUsername());
        if (uservo != null) {
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();

    }

    /*
    注册
     */
    @ApiOperation("登录功能")
    @PostMapping(value = "login")
    public JsonResult usersLogin(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO" + "=" + userLoginDTO);
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO != null) {
            if (userVO.getPassword().equals(userLoginDTO.getPassword())) {
                session.setAttribute("user", userVO);
                return new JsonResult(StatusCode.LOGIN_SUCCESS);
            } else {
                return new JsonResult(StatusCode.PASSWORD_ERROR);
            }
        }
        return new JsonResult(StatusCode.USERNAME_ERROR);
    }


    /*
    获取当前用户功能
     */
    @ApiOperation("用户登录状态获取功能")
    @GetMapping(value = "currentUser")
    public JsonResult getCurrentUser(@ApiIgnore HttpSession session) {
        UserVO uservo = (UserVO) session.getAttribute("user");
        return JsonResult.ok(uservo);
    }

    @ApiOperation("退出功能")
    @GetMapping(value = "logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }
}